package com.lovesoft.prologer.core.storage;

import java.awt.Dimension;
import java.awt.Point;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.TreeMap;

import com.lovesoft.prologer.Setup;
import com.lovesoft.prologer.core.LogID;
import com.lovesoft.prologer.tools.Freezer;

/**
 * Save and load application state to disk. Not really good implementation ....
 * 
 * @author Patryk 2014-10-01
 * 
 */
public class ApplicationStateStorage {
	private Freezer<String, Serializable> freezer;

	private static final String PREFIX_LOG_ID = "LOGID__";
	private static final String PREFIX_GUI_STATE = "GUISTATE__";
	private static final String PREFIX_GUI_STATE_LOCATION = PREFIX_GUI_STATE + "location";
	private static final String PREFIX_GUI_STATE_SIZE = PREFIX_GUI_STATE + "size";

	public ApplicationStateStorage() {
		freezer = new Freezer<>(Setup.getConfigurationFilePath());
	}

	public void save(ApplicationState as) throws IOException {
		Map<String, Serializable> toFreeze = new TreeMap<>();

		// Freeze logids
		int i = 0;
		for (LogID id : as.getLogIds()) {
			toFreeze.put(PREFIX_LOG_ID + i, id.storageToString());
			++i;
		}

		// Freeze GUI state
		toFreeze.put(PREFIX_GUI_STATE_LOCATION, as.getGuiState().getLocationOnScreen());
		toFreeze.put(PREFIX_GUI_STATE_SIZE, as.getGuiState().getSize());

		freezer.freeze(toFreeze);
	}

	public ApplicationState load() {
		try {
			Map<String, Serializable> state = freezer.defrost();
			ApplicationState as = new ApplicationState();
			for (String key : state.keySet()) {
				if (key.startsWith(PREFIX_LOG_ID)) {
					String data = (String) state.get(key);
					LogID id = new LogID();
					id.buildFromString(data);
					as.getLogIds().add(id);
				} else if (key.equals(PREFIX_GUI_STATE_LOCATION)) {
					Point locationOnScreen = (Point) state.get(key);
					as.getGuiState().setLocationOnScreen(locationOnScreen);
				} else if (key.equals(PREFIX_GUI_STATE_SIZE)) {
					Dimension size = (Dimension) state.get(key);
					as.getGuiState().setSize(size);
				} else {
					throw new RuntimeException("Unknown key for storage " + key);
				}
			}
			return as;
		} catch (IOException e) {
			return null;
		}
	}

}
